import crypto from 'crypto-js'
import base64 from 'base-64'
import utf8 from 'utf8'
import { queryOssGetStsToken } from '@/api/oss.js'

export const uploadOssMixins = {
  data() {
    return { formData: {}, }
  },
  methods: {
    // 获取直传OSS所需的参数配置项
    async getFormDataParams(user_id) {
		  // 获取STS临时token
		  const credentials = await queryOssGetStsToken()
		  const policyText = this.getPolicyBase64()
		  const uft8Str = utf8.encode(JSON.stringify(policyText))
		  const policy = base64.encode(uft8Str)
		  const signature = this.computeSignature(credentials.AccessKeySecret, policy)
		
		
		  const callback = {
		    // 设置回调请求的服务器地址，且要求必须为公网地址。
		    callbackUrl: credentials.callbackUrl,
		    // 设置回调请求消息头中Host的值，即您的服务器配置的Host值。
		    // host: 'yourHost',
		    // 设置发起回调时请求body的值。
		    callbackBody: 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&type=avatar&user_id=' +
						user_id,
		    // 设置发起回调请求的Content-Type。
		    callbackBodyType: 'application/x-www-form-urlencoded',
		  }
		  const uft8Str_callback = utf8.encode(JSON.stringify(callback))
		  const base64_callback = base64.encode(uft8Str_callback)
		  const formData = {
		    OSSAccessKeyId: credentials.AccessKeyId,
		    signature,
		    policy,
		    'success_action_status': '200',
		    'x-oss-security-token': credentials.SecurityToken,
		    callback: base64_callback,
		  }
		  this.formData = formData
    },
		
    // 执行上传，并且上传成功后，OSS去调用callback接口
    uploadFile(filePath, successc, failc) {
		  const _this = this
		  // 获取上传的文件类型
		  let fileTypeIndex = filePath.lastIndexOf('.')
		  let fileType = filePath.substring(fileTypeIndex)
      const dir = 'tmp/'
		  //图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
		  // const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
		  const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + fileType
		
		  uni.uploadFile({
		    url: 'https://playlet-video-asset.oss-cn-shenzhen.aliyuncs.com', //开发者服务器 url
		    filePath: filePath, //要上传文件资源的路径
		    name: 'file', //必须填file
		    formData: {
		      'key': aliyunFileKey,
		      ...this.formData
		    },
		    callback: this.formData.callback,
		    success: function(res) {
		      const resObj = JSON.parse(res.data)
          successc(resObj)
		      console.log('上传成功===', resObj)
		    },
		    fail: function(err) {
		      uni.showModal({ content: JSON.stringify(err) })
		      failc(err)
		    },
		  })
    },
		
    // 计算签名。
    computeSignature(accessKeySecret, canonicalString) {
		  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret))
    },
		
    getPolicyBase64() {
		  const date = new Date()
		  date.setHours(date.getHours() + 1)
		  const policyText = {
		    expiration: date.toISOString(), // 设置policy过期时间。
		    conditions: [
		      // 限制上传大小。
		      ['content-length-range', 0, 1024 * 1024 * 1024],
		    ],
		  }
		  return policyText
    },
		
  }
}
